package ustc.running.ui;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import ustc.running.R;
import ustc.running.broadcastReceiver.MediaButtonReceiver;
import ustc.running.util.TtsPlayer;
import ustc.running.util.VibratorUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 主页面
 * 
 * @author 李跃东
 * @mail androiddevelop@qq.com
 * @date 2013-11-7
 */
public class MainUi extends Activity {

	private TextView numberTv;
	private int number = 0;
	private BroadcastReceiver receiver;
	private WakeLock wakeLock = null;
	private AudioManager am;
	private ComponentName componentName;
	private TtsPlayer tts;
	private long startTime = 0;
	private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	private SimpleDateFormat sdf = new SimpleDateFormat("mm：ss",
			Locale.getDefault());

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setTitle(getResources().getString(R.string.app_name));
		setContentView(R.layout.main_ui);

		numberTv = (TextView) findViewById(R.id.number);
		numberTv.setText("0");

		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		componentName = new ComponentName(MainUi.this,
				MediaButtonReceiver.class);
		am.registerMediaButtonEventReceiver(componentName);
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("honest.ustc.COUNT");
		registerReceiver(receiver, filter);
		tts = new TtsPlayer(MainUi.this);

	}

	@Override
	protected void onResume() {
		acquireWakeLock();
		super.onResume();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, getResources().getString(R.string.clear));
		menu.add(0, 1, 1, getResources().getString(R.string.look));
		menu.add(0, 2, 2, getResources().getString(R.string.about_software));
		menu.add(0, 3, 3, getResources().getString(R.string.exit));
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			number = 0;
			numberTv.setText(number + "");
			VibratorUtil.vibrateOnce(this);
			startTime = 0;
			data.clear();
			break;
		case 1:
			Intent intent0 = new Intent(MainUi.this, RecorderUi.class);
			intent0.putExtra("data", (Serializable) data);
			MainUi.this.startActivity(intent0);
			break;
		case 2:
			Intent intent1 = new Intent(MainUi.this, AboutSoftwareUi.class);
			MainUi.this.startActivity(intent1);
			break;
		case 3: {
			new AlertDialog.Builder(MainUi.this)
			.setMessage(getResources().getString(R.string.really_exit))
			.setPositiveButton(getResources().getString(R.string.yes),
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					MainUi.this.finish();
				}
			})
			.setNegativeButton(getResources().getString(R.string.no),
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {

				}
			}).show();
		}
		break;
		}
		return true;
	}

	// 获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
	private void acquireWakeLock() {
		if (null == wakeLock) {
			PowerManager pm = (PowerManager) this
					.getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
					| PowerManager.ON_AFTER_RELEASE, getClass()
					.getCanonicalName());
			if (null != wakeLock) {
				wakeLock.acquire();
			}
		}
	}

	// 释放设备电源锁
	private void releaseWakeLock() {
		if (null != wakeLock) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	/**
	 * 点击返回键操作
	 */
	private long exitTime = 0;

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(MainUi.this,
						getResources().getString(R.string.press_again_to_exit),
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		if (receiver != null)
			unregisterReceiver(receiver);
		am.unregisterMediaButtonEventReceiver(componentName);
		releaseWakeLock();
		tts.stop();
		super.onDestroy();
	}

	public class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			Bundle data = intent.getExtras();
			long eventTime = data.getLong("event_time");
			int keyCode = data.getInt("key_code");
			switch (keyCode) {
			case KeyEvent.KEYCODE_HEADSETHOOK:// 播放或暂停
				playAndUpdate(eventTime);
				break;
			case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:// 播放或暂停
				playAndUpdate(eventTime);
				break;
			}
		}

	}

	/**
	 * 接收按键后开始操作
	 */
	private void playAndUpdate(long eventTime) {

		if (eventTime > 500) {
			if (startTime == 0) {
				startTime = System.currentTimeMillis();
				tts.play(MainUi.this.getResources().getString(
						R.string.start_to_record));
				return;
			}
			
			number++;
			numberTv.setText(number + "");
			
			long tmp = System.currentTimeMillis();
			long interval = tmp - startTime;
			String formatTime = sdf.format(interval);
			Map<String, String> map = new HashMap<String, String>();
			map.put("number", "" + number);
			map.put("time", formatTime);
			data.add(map);
			startTime = tmp;
			int index = formatTime.indexOf("：");
			tts.play(MainUi.this
					.getResources()
					.getString(R.string.record_success)
					.replaceFirst("\\$1", "" + number)
					.replaceFirst(
							"\\$2",
							Integer.valueOf(formatTime.substring(0, index))
							+ "")
							.replaceFirst(
									"\\$3",
									Integer.valueOf(formatTime.substring(index + 1))
									+ ""));
			VibratorUtil.vibrateTwice(MainUi.this);
		} else {
			if (startTime == 0) {	
				tts.play(MainUi.this.getResources()
						.getString(R.string.long_press_to_start_record));
				return ;
			}
			tts.play(MainUi.this.getResources()
					.getString(R.string.speak_recorder)
					.replaceFirst("\\$1", "" + number));
		}
	}
}
